﻿@using Microsoft.AspNetCore.SignalR.Client

@{
    ViewData["Title"] = "SignalR";
}

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card">
                <div class="card-header">聊天室</div>
                <div class="card-body">
                    <div id="messagesList" class="mb-3" style="height: 300px; overflow-y: auto; border: 1px solid #ccc; padding: 10px;"></div>
                    <div class="input-group">
                        <input type="text" id="userInput" class="form-control" placeholder="您的名称" />
                        <input type="text" id="messageInput" class="form-control" placeholder="要发送的内容" />
                        <button id="sendButton" class="btn btn-primary">发送</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="~/js/signalr.min.js"></script>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        // 创建 SignalR 连接
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chatHub")
            .build();

        // 处理接收到的消息
        connection.on("ReceiveMessage", (user, message) => {
            const msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
            const encodedMsg = `${user}: ${msg}`;
            const li = document.createElement("li");
            li.textContent = encodedMsg;
            document.getElementById("messagesList").appendChild(li);
        });

        // 启动连接
        connection.start()
            .catch(err => console.error(err.toString()));

        // 发送消息并清空输入框
        document.getElementById("sendButton").addEventListener("click", event => {
            sendMessage();
            event.preventDefault();
        });

        // 支持按 Enter 键发送消息
        document.getElementById("messageInput").addEventListener("keypress", event => {
            if (event.key === "Enter") {
                event.preventDefault();
                sendMessage();
            }
        });

        // 将发送逻辑封装为一个函数，避免代码重复
        function sendMessage() {
            const user = document.getElementById("userInput").value;
            const message = document.getElementById("messageInput").value;

            if (message.trim() === "") {
                alert("请输入消息内容！");
                return;
            }

            connection.invoke("SendMessage", user, message)
                .catch(err => console.error(err.toString()));

            // 清空消息输入框并聚焦
            document.getElementById("messageInput").value = "";
            document.getElementById("messageInput").focus();
        }
    });
</script>